# selenium 4
from selenium.webdriver import Keys
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC

import time
import uuid
import os
from utils import image_to_text


def login(driver, web, *args, **kwargs):
    url = kwargs.get('url')
    username = kwargs.get('username')
    password = kwargs.get('password')
    print(url)
    driver.get(url)
    # username
    web.until(
        EC.visibility_of_element_located((By.XPATH, "//input[@placeholder='请输入账号']"))
    ).send_keys(username, Keys.TAB)
    # password
    web.until(
        EC.visibility_of_element_located((By.XPATH, "//input[@placeholder='请输入密码']"))
    ).send_keys(password, Keys.TAB)

    canvas_input = web.until(
        EC.visibility_of_element_located((By.XPATH, "//input[@placeholder='请输入验证码']"))
    )
    #  找到验证码
    canvas = web.until(
        EC.visibility_of_element_located((By.TAG_NAME, 'canvas'))
    )

    login_button = web.until(
        EC.visibility_of_element_located((By.XPATH, "//button/span[text()='登 录']"))
    )

    local_path = os.path.dirname(__file__)
    canvas_path = os.path.join(local_path, 'screenshots')

    # 如果识别的图片文字不是4位数，则重新生成
    while True:
        print('开始识别验证码')
        # 截图验证码

        filename = os.path.join(canvas_path, str(uuid.uuid4()) + '.png')
        print(filename)

        canvas.screenshot(filename)
        time.sleep(1)
        # 验证图片
        if os.path.exists(filename):
            img_txt = image_to_text(filename)
            print(img_txt)
            if len(img_txt) == 4:
                # 如果是4位数，尝试输入验证码
                # 验证码
                canvas_input.clear()
                canvas_input.send_keys(img_txt)
                login_button.click()
                time.sleep(1)
                # 尝试获取token
                token = driver.execute_script("return window.localStorage.getItem('token');")
                print('token is: ', token)
                # 获取当前URL
                current_url = driver.current_url
                if current_url.__contains__('user-manage'):
                    print('登录成功')
                    break
        # 更新验证码
        canvas.click()
